package redis

import (
	"fmt"
	"github.com/go-redis/redis"
	"strings"
	"time"
)

var Rdb *redis.Client

func InitClient(ipaddr, password string) (err error) {
	Rdb = redis.NewClient(&redis.Options{
		Addr:     ipaddr,
		Password: password,
		DB:       0,
	})

	_, err = Rdb.Ping().Result()
	if err != nil {
		fmt.Printf("redis connect failed, err:%s\n", err)
		return err
	}
	fmt.Println("redis connect succeed!")
	return nil
}

func WatchFunct(key string) []string {

	err := Rdb.Watch(func(tx *redis.Tx) error {
		//str := tx.Get(key).String()
		str, _ := Rdb.Get(key).Result()
		_, err := tx.TxPipelined(func(pipeliner redis.Pipeliner) error {
			time.Sleep(time.Second * 1)
			pipeliner.Set(key, str, 0)
			return nil
		})
		return err
	}, key)
	str, _ := Rdb.Get(key).Result()
	if err != nil {
		fmt.Println("tx exec failed:", err)
		//fmt.Println("then key is :",str)

		dirmap := strings.Split(strings.Replace(str, " ", "", -1), ",")
		//fmt.Println(dirmap)
		return dirmap
	}
	//fmt.Println("tx exec success ,then key is :",str)
	dirmap := strings.Split(strings.Replace(str, " ", "", -1), ",")
	//fmt.Println(dirmap)
	return dirmap
}

